package edu.itstudy.control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.itstudy.bean.User;
import edu.itstudy.services.IUserServices;
import edu.itstudy.services.impl.IUserServicesImpl;

public class LoginServlet extends HttpServlet {
	
private IUserServices iuserServices = new IUserServicesImpl();
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 获取用户登录信息
		 * 把信息交给services帮忙登录
		 * services把登录结果告诉servlet
		 * services要DAO判断用户名和密码是否正确，DAO告诉services查询结果
		 * DAO通过JDBC连接数据库操作
		 * 根据services登录结果响应用户		
		 * true 回首页
		 * false 跑到登录页面，提示登录失败
		 */
		request.setCharacterEncoding("UTF-8");;
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		
		User user = new User();
		user.setName(name);
		user.setPassword(password);
		
		boolean result = iuserServices.login(user);
		
		//业务流程控制
		if(result) {
			//把用户名存入到session对象中
			request.getSession().setAttribute("name",name);
			
			response.sendRedirect("index");
		}else {
			request.setAttribute("info","用户名或密码错误！");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}
}
